import { Component, EventEmitter, Input, Output } from '@angular/core';
import { MenuDto } from '../../models/sys/menu.dto';

@Component({
  selector: 'app-menu-tree',
  templateUrl: './menu-tree.component.html',
  styleUrl: './menu-tree.component.css'
})
export class MenuTreeComponent {
  @Input() withCheckbox!: boolean;
  @Input() menus: MenuDto[] = [];
  @Input() expand = true;

  @Input() selectedNode: MenuDto = new MenuDto();
  @Output() selectedNodeChange = new EventEmitter<MenuDto>();
  
  @Output() nodeSelected = new EventEmitter<MenuDto>();

  clickItem(menu: MenuDto) {
    console.log(`in tree - Selected menu: ${menu.menuName}:${menu.path}`);
    this.selectedNode = menu;
    this.nodeSelected.emit(this.selectedNode);
  }

  childClickItem(menu: MenuDto) {
    console.log(`in tree, child selected ${menu.menuName}:${menu.path}`);
    this.nodeSelected.emit(menu);
  }

  checked(menu: MenuDto) {
    menu.checked = !menu.checked;
    this.setChildrenChecked(menu, menu.checked);
    this.setParentChecked(menu, menu.checked);
  }

  setChildrenChecked(menu: MenuDto, checked: boolean) {
    menu.checked = checked;

    for (let child of menu.children) {
      this.setChildrenChecked(child, checked);
    }
  }

  setParentChecked(menu: MenuDto, checked: boolean) {
    let parent = menu.parent;
    while (parent) {
      let uncheckedChild = parent.children.find(x => !x.checked);
      if (uncheckedChild) {
        parent.checked = false;
      } else {
        parent.checked = true;
      }

      /** 再向上一级 */
      parent = parent.parent;
    }
  }
}
